namespace Bowlus.FrontEnd.RequestRouting.ApplicationDeployment
{
    using System;
    using Bowlus.Common;
    using Bowlus.Common.Communications;

    public class AddApplicationRequest : ApplicationDeploymentRequest
    {
        public AddApplicationRequest(TenantDeployment tenantDeployment, ApplicationHost applicationHost)
            : base(tenantDeployment)
        {
            this.ToHost = applicationHost;
        }

        private ApplicationHost ToHost { get; set; }

        public override Guid SendDeploymentRequest()
        {
            var deploymentServiceClient = new CommunicationsClient();

            var message = this.ConstructMessage(BowlusMessageType.DeployApp);

            deploymentServiceClient.SendMessageToRoleInstance(message, this.ToHost.DeploymentManagerEndpoint, Settings.AppHostRoleName);
            this.TenantDeployment.Status = TenantDeploymentStatus.DeployRequestSubmitted;
            TenantDeploymentsStore.UpdateDeploymentStore(this.TenantDeployment);

            return message.MessageId;
        }

        public override bool CanUpdateConfiguration(BowlusMessage response, out Guid nextMessageId)
        {
            // If failed, result code is already in the message for delete and deploy app.
            nextMessageId = Guid.Empty;

            if (response.MessageType == BowlusMessageType.AppDeployed)
            {
                return true;
            }

            return false;
        }
    }
}